package com.client;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

import util.Util;

public class CommandReceiver extends Thread {
	private InputStream	is;
	private Monitor		m;

	public CommandReceiver(Socket s, Monitor m)
	{
		this.m = m;
		try
		{
			is = s.getInputStream();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void run()
	{
		while (true)
		{
			try
			{
				byte[] receiveSize = new byte[4];
				is.read(receiveSize);
				int packageSize = ByteBuffer.wrap(receiveSize).getInt();
				if (packageSize >= 0)
				{
					byte[] b = new byte[4 + packageSize];
					Util.fill(b, receiveSize, 0);
					is.read(b, 4, packageSize);
					m.put(b);
				}

			} catch (IOException e)
			{
				System.out.println("Lost connection to the server. Please try restarting the applet.");
				System.exit(1);
			}
		}
	}

}
